/*
 * Copyright (C) Ruslan Mikhaylenko 10.11.2011 mirusnet@gmail.com 
 */

#include <my_global.h>
#include <mysql.h>
#include <time.h>


#define hostname "localhost" 
#define username "root" 
#define password NULL  
#define dbname "mirus" 

MYSQL *connection;
MYSQL_RES *res;
MYSQL_ROW row;


int transactions = 1000;

void test_insert(int max, int type)
{
	//printf(" ");
        if(type) {
	for(int i=0; i<max; i++) {
		mysql_query(connection, "INSERT into test_innodb(data) values('99c2c51f4a47926e22719dc3742d8952');");
		//printf("%d\r", i);
		}
	} else {
        for(int i=0; i<max; i++) {
                mysql_query(connection, "INSERT into test_myisam(data) values('99c2c51f4a47926e22719dc3742d8952');");
		//printf("%d\r", i);
		}
	}
	printf("%d rows inserted\t", max);
}


void clean_tables()
{
        printf("Truncating table\tmirus.test_innodb\n");
        mysql_query(connection, "truncate table mirus.test_innodb;");
	//printf("%ld\trows deleted\n", (long) mysql_affected_rows(connection));
	printf("Truncating table\tmirus.test_myisam\n");
        mysql_query(connection, "truncate table mirus.test_myisam;");
	//printf("%ld\trows deleted\n", (long) mysql_affected_rows(connection));	

}


void test_io_innodb()
{
	time_t start, end;
        char buffer[200];
	printf("Testing InnoDB I/O:\n");
        for(int i=0; i<3; i++) {
                snprintf(buffer, 200, "set global innodb_flush_log_at_trx_commit = %d;", i);
                printf("innodb_flush_log_at_trx_commit %d\t", i);
                mysql_query(connection, buffer);
                time(&start);
                test_insert(transactions, 1);
                time(&end);
                printf("Finished in %.0f\tseconds. \n", difftime(end, start));
        }
	printf("\n\n");
}

void test_io_myisam()
{
	time_t start, end;
	printf("Testing MyIsam I/O:\n");
	time(&start);
	test_insert(transactions, 0);
	time(&end);
	printf("Finished in %.0f seconds. \n", difftime(end, start));
	printf("\n");
}

void test_select()
{
	mysql_query(connection,"select * from mirus.test_innodb order by id;");
	res = mysql_store_result(connection);
	while((row = mysql_fetch_row(res))) {
		//for (int i=0 ; i < (int)mysql_num_fields(res); i++) 
			//printf("%s\t%s\n",row[0], row[1]);
	}
	mysql_free_result(res);
	
}


int main(int argc, char **argv)
{

	connection = mysql_init(NULL);
	if(!mysql_real_connect(connection, hostname, username, password, dbname, 3306, NULL, 0)){
		fprintf(stderr, "%s\n", mysql_error(connection));
		return 1;
		}

	test_io_innodb();
	test_io_myisam();
	test_select();	
	clean_tables();
	
	mysql_close(connection);
	
	return 0;
}
